/**
 * hnjz.com Inc.
 * Copyright (c) 2004-2014 All Rights Reserved.
 */
package com.hnjz.sys.roleFun;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hnjz.common.AppException;
import com.hnjz.common.PKUtil;
import com.hnjz.common.YnEnum;
import com.hnjz.common.security.CtxUtil;
import com.hnjz.common.security.SecurityData;
import com.hnjz.sys.function.FunMapper;
import com.hnjz.sys.function.FuncOper;
import com.hnjz.sys.function.FuncOperMapper;
import com.hnjz.sys.function.Function;
import com.hnjz.sys.role.Role;
import com.hnjz.sys.role.RoleMapper;
import com.hnjz.sys.user.User;

/**
 * 权限管理的Manager
 * 
 * @author wumi
 * @version $Id: RoleFuncManager.java, v 0.1 Feb 14, 2014 9:15:39 AM wumi Exp $
 */
@Service("roleFuncManager")
public class RoleFuncManager {

    /**日志*/
    private static final Log    log     = LogFactory.getLog(RoleFuncManager.class);

    private static final String HOUZHUI = "ww";

    @Autowired
    private SecurityData        securityData;
    @Autowired
    private RoleMapper          roleMapper;
    @Autowired
    private RoleFuncOperMapper  roleFuncOperMapper;
    @Autowired
    private RoleFuncMapper      roleFuncMapper;
    @Autowired
    private FuncOperMapper      funcOperMapper;
    @Autowired
    private FunMapper           funMapper;

    /**
     * 查询功能菜单
     * 
     * @return 功能菜单列表
     * @throws Exception 
     */
    public JSONArray queryQuxian(String role) throws Exception {
        JSONArray re = new JSONArray();
        List<Function> pos = this.funMapper.findList();
        List<FuncOper> ops = this.funcOperMapper.findList();
		List<RoleFunc> rfus = null;
        List<RoleFuncOper> rops = null;
        List<String> rfids = new ArrayList<String>();
        List<String> ropids = new ArrayList<String>();
        
        if (StringUtils.isNotBlank(role)) {
        	rfus = this.roleFuncMapper.findByRoleId(role);
        	for(RoleFunc rf:rfus){
        		rfids.add(rf.getFunc());
        	}
        	rops = this.roleFuncOperMapper.findByRole(role);
        	for(RoleFuncOper rfo:rops){
        		ropids.add(rfo.getFo());
        	}
        }
        //Map<String, Collection<ConfigAttribute>> resourceMap = securityData.getResourceMap();
        JSONObject o = null;
        for (Function ele : pos) {
            o = new JSONObject();
            o.put("id", ele.getId());
            if (StringUtils.isNotBlank(ele.getParent())) {
                o.put("pid", ele.getParent());
            }
            o.put("name", ele.getFuncName());
            o.put("checked", rfids.contains(ele.getId()));
            re.put(o);
        }
        for (FuncOper ele : ops) {
            o = new JSONObject();
            o.put("id", ele.getId().concat(HOUZHUI));
            if (StringUtils.isNotBlank(ele.getFunction())) {
                o.put("pid", ele.getFunction());
            }
            o.put("name", ele.getName());
            o.put("checked", ropids.contains(ele.getId()));
            re.put(o);
        }
        

        return re;
    }

    /**
     * 保存权限
     * 
     * @param roleId 角色id
     * @param roleFuncIds 角色所具有的权限
     * @throws AppException 
     */
    public void saveQuanxian(String roleId, String roleFuncIds) throws AppException {
        if (StringUtils.isBlank(roleFuncIds)) {
            throw new AppException("请选择功能和操作");
        }
        String[] ids = roleFuncIds.split(",");
        User user = CtxUtil.getCurUser();
        Role role = roleMapper.findById(roleId);
        if (null == role) {
            throw new AppException("请选择角色");
        }
        Date cur = new Date();
        //删除所有角色数据
        this.roleFuncMapper.deleteByRoleId(roleId);
        this.roleFuncOperMapper.deleteByRoleId(roleId);
        //保存权限所具有的操作
        RoleFunc roleFunc = null;
        RoleFuncOper roleFuncOper = null;
        for (String ele : ids) {
            if (StringUtils.isBlank(ele)) {
                continue;
            }
            //保存功能对应的操作
            if (ele.length() == 34) {
                ele = ele.substring(0, 32);
                roleFuncOper = new RoleFuncOper();
                FuncOper fuc = this.funcOperMapper.findById(ele);
                //操作
                if (log.isDebugEnabled()) {
                    log.debug("id:" + ele + "---name:" + fuc.getName());
                }
                roleFuncOper.setId(PKUtil.uuid());
                roleFuncOper.setFo(ele);
                roleFuncOper.setFun(StringUtils.defaultIfBlank(fuc.getFunction(), ""));
                roleFuncOper.setFo(ele);
                roleFuncOper.setRole(roleId);
                roleFuncOper.setCreater(user.getId());
                roleFuncOper.setCreateTime(cur);
                roleFuncOper.setIsActive(YnEnum.Y.getCode());
                roleFuncOper.setOrderBy(0);
                roleFuncOper.setNote("");
                this.roleFuncOperMapper.save(roleFuncOper);
                //保存功能
            } else if (ele.length() == 32) {
                roleFunc = new RoleFunc();
                roleFunc.setId(PKUtil.uuid());
                roleFunc.setCreater(user.getId());
                roleFunc.setCreateTime(cur);
                roleFunc.setFunc(ele);
                roleFunc.setIsActive(YnEnum.Y.getCode());
                roleFunc.setOrderBy(0);
                roleFunc.setRole(roleId);
                roleFunc.setNote("");
                this.roleFuncMapper.save(roleFunc);
            }
        }

        securityData.loadAllResource();
    }

    public SecurityData getSecurityData() {
        return securityData;
    }

    public void setSecurityData(SecurityData securityData) {
        this.securityData = securityData;
    }

}
